<template>
  <el-dialog 
    v-model="visible" 
    title="AI生成章节内容" 
    width="1200px" 
    @close="handleClose"
  >
    <div class="chapter-generate-content">
      <!-- 顶部配置区域 -->
      <div class="generate-config-section">
      </div>

      <el-row :gutter="20" style="margin-top: 16px;">
        <!-- 左侧：素材选择 -->
        <el-col :span="14">
          <div class="materials-section">
            <div class="section-header">
              <h4 class="section-title">📚 创作素材</h4>
              <el-button size="small" @click="clearAllMaterials">清空选择</el-button>
            </div>

            <!-- 素材选择标签页 -->
            <el-tabs v-model="activeMaterialTab" class="materials-tabs">
              <el-tab-pane label="👥 人物角色" name="characters">
                <div class="tab-header">
                  <span class="tab-count">已选择 {{ selectedMaterials.characters.length }}/{{ characters.length }}</span>
                  <el-button size="small" @click="selectAllMaterials('characters')" v-if="characters.length > 0">全选</el-button>
                </div>
                <div class="materials-grid">
                  <div
                    v-for="character in characters"
                    :key="character.id"
                    class="material-card"
                    :class="{ selected: selectedMaterials.characters.some(c => c.id === character.id) }"
                    @click="toggleMaterial('characters', character)"
                  >
                    <div class="material-header">
                      <span class="material-name">{{ character.name }}</span>
                      <el-tag :type="getRoleType(character.role)" size="small">{{ getRoleText(character.role) }}</el-tag>
                    </div>
                    <p class="material-desc">{{ character.personality?.substring(0, 40) || '暂无描述' }}...</p>
                    <div class="material-tags">
                      <el-tag v-for="tag in character.tags?.slice(0, 2)" :key="tag" size="small">{{ tag }}</el-tag>
                    </div>
                  </div>
                </div>
                <div v-if="characters.length === 0" class="empty-materials">
                  <p>暂无人物角色</p>
                </div>
              </el-tab-pane>

              <el-tab-pane label="🌍 世界观" name="worldSettings">
                <div class="tab-header">
                  <span class="tab-count">已选择 {{ selectedMaterials.worldSettings.length }}/{{ worldSettings.length }}</span>
                  <el-button size="small" @click="selectAllMaterials('worldSettings')" v-if="worldSettings.length > 0">全选</el-button>
                </div>
                <div class="materials-grid">
                  <div
                    v-for="setting in worldSettings"
                    :key="setting.id"
                    class="material-card"
                    :class="{ selected: selectedMaterials.worldSettings.some(w => w.id === setting.id) }"
                    @click="toggleMaterial('worldSettings', setting)"
                  >
                    <div class="material-header">
                      <span class="material-name">{{ setting.title }}</span>
                      <el-tag v-if="setting.category" size="small">{{ setting.category }}</el-tag>
                    </div>
                    <p class="material-desc">{{ setting.description?.substring(0, 50) || '暂无描述' }}...</p>
                  </div>
                </div>
                <div v-if="worldSettings.length === 0" class="empty-materials">
                  <p>暂无世界观设定</p>
                </div>
              </el-tab-pane>

              <el-tab-pane label="📝 语料库" name="corpus">
                <div class="tab-header">
                  <span class="tab-count">已选择 {{ selectedMaterials.corpus.length }}/{{ corpusData.length }}</span>
                  <el-button size="small" @click="selectAllMaterials('corpus')" v-if="corpusData.length > 0">全选</el-button>
                </div>
                <div class="materials-grid">
                  <div
                    v-for="corpus in corpusData"
                    :key="corpus.id"
                    class="material-card"
                    :class="{ selected: selectedMaterials.corpus.some(c => c.id === corpus.id) }"
                    @click="toggleMaterial('corpus', corpus)"
                  >
                    <div class="material-header">
                      <span class="material-name">{{ corpus.title }}</span>
                    </div>
                    <p class="material-desc">{{ corpus.content?.substring(0, 40) || '暂无内容' }}...</p>
                  </div>
                </div>
                <div v-if="corpusData.length === 0" class="empty-materials">
                  <p>暂无语料库</p>
                </div>
              </el-tab-pane>

              <el-tab-pane label="📅 事件线" name="events">
                <div class="tab-header">
                  <span class="tab-count">已选择 {{ selectedMaterials.events.length }}/{{ events.length }}</span>
                  <el-button size="small" @click="selectAllMaterials('events')" v-if="events.length > 0">全选</el-button>
                </div>
                <div class="materials-grid">
                  <div
                    v-for="event in events"
                    :key="event.id"
                    class="material-card"
                    :class="{ selected: selectedMaterials.events.some(e => e.id === event.id) }"
                    @click="toggleMaterial('events', event)"
                  >
                    <div class="material-header">
                      <span class="material-name">{{ event.title }}</span>
                      <el-tag :type="getImportanceType(event.importance)" size="small">第{{ event.chapter }}章</el-tag>
                    </div>
                    <p class="material-desc">{{ event.description?.substring(0, 40) || '暂无描述' }}...</p>
                    <div class="material-meta">
                      <span class="event-time">{{ event.time || '时间未定' }}</span>
                    </div>
                  </div>
                </div>
                <div v-if="events.length === 0" class="empty-materials">
                  <p>暂无事件线</p>
                </div>
              </el-tab-pane>

              <el-tab-pane label="📖 上下文内容" name="chapters">
                <div class="tab-header">
                  <span class="tab-count">已选择 {{ selectedContextChapters.length }}/{{ availableContextChapters.length }}</span>
                  <div class="context-tab-actions">
                    <el-button size="small" @click="selectAllContextChapters" v-if="availableContextChapters.length > 0">全选</el-button>
                  </div>
                </div>
                <div class="materials-list">
                  <div
                    v-for="chapter in availableContextChapters"
                    :key="chapter.id"
                    class="chapter-material-card"
                    :class="{ selected: selectedContextChapters.includes(chapter.id) }"
                    @click="toggleContextChapter(chapter.id)"
                  >
                    <div class="chapter-material-header">
                      <span class="chapter-material-name">第{{ chapter.chapterIndex }}章 {{ chapter.title }}</span>
                      <div class="chapter-material-tags">
                        <el-tag :type="getChapterStatusType(chapter.status)" size="small">{{ getChapterStatusText(chapter.status) }}</el-tag>
                        <el-tag size="small" type="info">{{ chapter.wordCount }}字</el-tag>
                      </div>
                    </div>
                    <p class="chapter-material-desc">{{ chapter.description || '暂无大纲' }}</p>
                    <div v-if="chapter.content" class="chapter-material-content">
                      <span class="content-preview">{{ cleanHtmlForPreview(chapter.content, 80) }}...</span>
                    </div>
                  </div>
                </div>
                <div v-if="availableContextChapters.length === 0" class="empty-materials">
                  <p>暂无可选择的章节</p>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>

        <!-- 右侧：提示词选择 -->
        <el-col :span="10">
          <div class="prompt-section">
            <div class="section-header">
              <h4 class="section-title">📝 提示词模板</h4>
              <el-button size="small" @click="useDefaultPrompt">使用默认</el-button>
            </div>

            <!-- 提示词分类选择 -->
            <div class="category-selection-modern">
              <div class="category-header">
                <span>🏷️ 正文类型</span>
              </div>
              <div class="category-grid">
                <div
                  v-for="category in contentCategories"
                  :key="category.key"
                  class="category-card"
                  :class="{ active: selectedContentCategory === category.key }"
                  @click="selectedContentCategory = category.key"
                >
                  <span class="category-icon">{{ category.icon }}</span>
                  <span class="category-name">{{ category.name }}</span>
                </div>
              </div>
            </div>

            <!-- 提示词列表 -->
            <div class="prompt-selection-modern">
              <div class="prompt-header">
                <span>可用模板 ({{ getPromptsByCategory(selectedContentCategory).length }})</span>
                <el-button size="small" @click="refreshPrompts">刷新</el-button>
              </div>
              <div class="prompt-list-modern">
                <div
                  v-for="prompt in getPromptsByCategory(selectedContentCategory)"
                  :key="prompt.id"
                  class="prompt-item-modern"
                  :class="{ active: selectedPrompt?.id === prompt.id }"
                  @click="selectPromptForChapter(prompt)"
                >
                  <div class="prompt-content">
                    <h5 class="prompt-title">{{ prompt.title }}</h5>
                    <p class="prompt-desc">{{ prompt.description }}</p>
                    <div class="prompt-meta">
                      <div class="prompt-tags">
                        <el-tag v-for="tag in prompt.tags?.slice(0, 2)" :key="tag" size="small">{{ tag }}</el-tag>
                      </div>
                    </div>
                  </div>
                  <div class="prompt-actions">
                    <el-icon v-if="selectedPrompt?.id === prompt.id" class="selected-icon"><Check /></el-icon>
                  </div>
                </div>
              </div>
              <div v-if="getPromptsByCategory(selectedContentCategory).length === 0" class="empty-prompts">
                <p>暂无该类型的提示词模板</p>
              </div>
            </div>

            <!-- 变量填充区域 -->
            <div v-if="showVariablesSection" class="variables-section">
              <div class="variables-header">
                <span>📋 变量配置</span>
                <el-button size="small" @click="autoFillVariables">智能填充</el-button>
              </div>
              <div class="variables-form">
                <div
                  v-for="(value, variable) in promptVariables"
                  :key="variable"
                  class="variable-item"
                >
                  <label class="variable-label">{{ variable }}</label>

                  <!-- 前文概要使用章节多选框 -->
                  <div v-if="variable === '前文概要'" class="context-variable-container">
                    <el-select
                      v-model="selectedContextChapters"
                      multiple
                      placeholder="选择章节作为前文参考"
                      @change="updateContextVariable"
                      size="small"
                      style="width: 100%"
                      max-collapse-tags="3"
                    >
                      <el-option
                        v-for="chapter in availableContextChapters"
                        :key="chapter.id"
                        :label="`第${chapter.chapterIndex}章 ${chapter.title} (${chapter.wordCount}字)`"
                        :value="chapter.id"
                      >
                        <div class="context-chapter-option">
                          <span class="chapter-title">第{{ chapter.chapterIndex }}章 {{ chapter.title }}</span>
                          <div class="chapter-meta">
                            <el-tag :type="getChapterStatusType(chapter.status)" size="small">{{ getChapterStatusText(chapter.status) }}</el-tag>
                            <span class="word-count">{{ chapter.wordCount }}字</span>
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                    <div class="context-actions">
                      <el-button size="small" @click="clearContextSelection" v-if="selectedContextChapters.length > 0">清空</el-button>
                    </div>
                  </div>

                  <!-- 其他变量使用普通输入框 -->
                  <el-input
                    v-else
                    v-model="promptVariables[variable]"
                    :type="['章节大纲', '主要人物', '世界观设定', '参考语料'].includes(variable) ? 'textarea' : 'text'"
                    :rows="2"
                    :placeholder="'请输入' + variable"
                    @input="generateFinalPrompt"
                    size="small"
                  />
                </div>
              </div>
            </div>

            <!-- 最终提示词预览 -->
            <div v-if="selectedPrompt" class="preview-section">
              <div class="preview-header">
                <span>👀 最终提示词</span>
                <div class="preview-actions">
                  <el-button size="small" @click="copyPrompt">复制</el-button>
                </div>
              </div>
              <div class="preview-content">
                <el-input
                  v-model="finalPrompt"
                  type="textarea"
                  :rows="8"
                  readonly
                  placeholder="请选择提示词并填充变量"
                  class="preview-textarea"
                />
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <div class="action-buttons">
          <el-button @click="visible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleGenerate"
            :loading="isGeneratingContent"
            :disabled="!selectedPrompt"
          >
            <el-icon><MagicStick /></el-icon>
            {{ isGeneratingContent ? '生成中...' : '开始生成' }}
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, MagicStick } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  currentChapter: {
    type: Object,
    default: null
  },
  currentNovel: {
    type: Object,
    default: null
  },
  characters: {
    type: Array,
    default: () => []
  },
  worldSettings: {
    type: Array,
    default: () => []
  },
  corpusData: {
    type: Array,
    default: () => []
  },
  events: {
    type: Array,
    default: () => []
  },
  chapters: {
    type: Array,
    default: () => []
  },
  availablePrompts: {
    type: Array,
    default: () => []
  },
  isGeneratingContent: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'generate'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 材料选择相关
const selectedMaterials = ref({
  characters: [],
  worldSettings: [],
  corpus: [],
  events: [],
  chapters: []
})

// 前文概要章节选择
const selectedContextChapters = ref([])

// 生成配置
const generateConfig = ref({
  wordCount: 3000,
  style: 'third-person',
  focus: ''
})

// 活动标签页
const activeMaterialTab = ref('characters')

// 正文生成分类
const contentCategories = ref([
  { key: 'content', name: '基础正文', icon: '📝' },
  { key: 'content-dialogue', name: '对话生成', icon: '💬' },
  { key: 'content-scene', name: '场景描写', icon: '🏞️' },
  { key: 'content-action', name: '动作情节', icon: '⚡' },
  { key: 'content-psychology', name: '心理描写', icon: '🧠' }
])

// 提示词相关
const selectedContentCategory = ref('content')
const selectedPrompt = ref(null)
const promptVariables = ref({})
const finalPrompt = ref('')

// 是否显示变量配置区域
const showVariablesSection = computed(() => {
  return selectedPrompt.value && Object.keys(promptVariables.value).length > 0
})

// 监听素材选择变化，自动更新变量
watch(
  [() => selectedMaterials.value.characters, () => selectedMaterials.value.worldSettings, () => selectedMaterials.value.corpus],
  () => {
    if (selectedPrompt.value && Object.keys(promptVariables.value).length > 0) {
      autoFillVariables()
    }
  },
  { deep: true }
)

// 监听标签页切换，确保变量配置区域正确显示
watch(activeMaterialTab, () => {
  // 切换标签页时，如果已有选中的提示词和变量，确保变量配置区域显示
  if (selectedPrompt.value && Object.keys(promptVariables.value).length > 0) {
    nextTick(() => {
      generateFinalPrompt()
    })
  }
})

// 可用的上下文章节
const availableContextChapters = computed(() => {
  if (!props.chapters) return []
  
  return props.chapters.filter(ch => {
    return ch.description || (ch.content && ch.content.trim())
  }).map(ch => ({
    id: ch.id,
    title: ch.title,
    description: ch.description,
    content: ch.content,
    status: ch.status,
    wordCount: ch.wordCount || 0,
    chapterIndex: getChapterIndex(ch)
  }))
})

// 工具方法
const getChapterIndex = (chapter) => {
  if (chapter.chapterOrder) {
    return chapter.chapterOrder
  }
  const localIndex = props.chapters.findIndex(ch => ch.id === chapter.id)
  if (localIndex >= 0) {
    return localIndex + 1
  }
  return 1
}

const cleanHtmlForPreview = (htmlContent, maxLength = 80) => {
  if (!htmlContent) return ''
  let cleanText = htmlContent.replace(/<[^>]*>/g, '')
  cleanText = cleanText
    .replace(/&nbsp;/g, ' ')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&amp;/g, '&')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
  cleanText = cleanText.replace(/\s+/g, ' ').trim()
  return cleanText.length > maxLength ? cleanText.substring(0, maxLength) : cleanText
}

const getRoleType = (role) => {
  const roleMap = {
    'protagonist': 'danger',
    'supporting': 'primary',
    'antagonist': 'warning',
    'minor': 'info'
  }
  return roleMap[role] || 'info'
}

const getRoleText = (role) => {
  const roleMap = {
    'protagonist': '主角',
    'supporting': '配角',
    'antagonist': '反派',
    'minor': '次要角色'
  }
  return roleMap[role] || '配角'
}

const getGenderText = (gender) => {
  const genderMap = {
    'male': '男',
    'female': '女',
    'other': '其他'
  }
  return genderMap[gender] || ''
}

const getChapterStatusType = (status) => {
  const statusMap = {
    draft: 'warning',
    completed: 'success',
    published: 'primary'
  }
  return statusMap[status] || 'warning'
}

const getChapterStatusText = (status) => {
  const statusMap = {
    draft: '草稿',
    completed: '完成',
    published: '发表'
  }
  return statusMap[status] || '草稿'
}

const getImportanceType = (importance) => {
  const typeMap = {
    'high': 'danger',
    'normal': 'primary',
    'low': 'info'
  }
  return typeMap[importance] || 'primary'
}

const getPromptsByCategory = (category) => {
  return props.availablePrompts.filter(prompt => prompt.category === category)
}

// 清空所有材料
const clearAllMaterials = () => {
  selectedMaterials.value = {
    characters: [],
    worldSettings: [],
    corpus: [],
    events: [],
    chapters: []
  }
  selectedContextChapters.value = []
  if (promptVariables.value['前文概要']) {
    promptVariables.value['前文概要'] = ''
    generateFinalPrompt()
  }
  ElMessage.success('已清空所有选择')
}

// 全选某类材料
const selectAllMaterials = (type) => {
  switch (type) {
    case 'characters':
      selectedMaterials.value.characters = [...props.characters]
      break
    case 'worldSettings':
      selectedMaterials.value.worldSettings = [...props.worldSettings]
      break
    case 'corpus':
      selectedMaterials.value.corpus = [...props.corpusData]
      break
    case 'events':
      selectedMaterials.value.events = [...props.events]
      break
  }
  ElMessage.success('已选择所有材料')
}

// 切换材料选择
const toggleMaterial = (type, material) => {
  const materials = selectedMaterials.value[type]
  const index = materials.findIndex(item => item.id === material.id)
  
  if (index > -1) {
    materials.splice(index, 1)
  } else {
    materials.push(material)
  }
}

// 选择提示词
const selectPromptForChapter = (prompt) => {
  selectedPrompt.value = prompt
  promptVariables.value = {}
  
  const matches = prompt.content.match(/\{([^}]+)\}/g)
  if (matches) {
    matches.forEach(match => {
      const variable = match.slice(1, -1)
      promptVariables.value[variable] = ''
    })
  }
  
  nextTick(() => {
    autoFillVariables()
  })
}

// 使用默认提示词
const useDefaultPrompt = () => {
  selectedPrompt.value = null
  promptVariables.value = {}
  finalPrompt.value = ''
  ElMessage.info('已切换到默认提示词')
}

// 刷新提示词
const refreshPrompts = async () => {
  ElMessage.success('提示词列表已刷新')
}

// 复制提示词
const copyPrompt = () => {
  if (finalPrompt.value) {
    navigator.clipboard.writeText(finalPrompt.value)
    ElMessage.success('提示词已复制到剪贴板')
  }
}

// 生成最终提示词
const generateFinalPrompt = () => {
  if (!selectedPrompt.value) {
    finalPrompt.value = ''
    return
  }
  
  let result = selectedPrompt.value.content
  Object.keys(promptVariables.value).forEach(variable => {
    const value = promptVariables.value[variable] || `{${variable}}`
    result = result.replace(new RegExp(`\\{${variable}\\}`, 'g'), value)
  })
  
  finalPrompt.value = result
}

// 自动填充变量
const autoFillVariables = () => {
  if (!selectedPrompt.value || !props.currentChapter) return
  
  promptVariables.value['小说标题'] = props.currentNovel?.title || '未命名小说'
  promptVariables.value['章节标题'] = props.currentChapter.title || ''
  promptVariables.value['章节大纲'] = props.currentChapter.description || '暂无大纲'
  promptVariables.value['目标字数'] = generateConfig.value.wordCount.toString()
  promptVariables.value['写作视角'] = getViewpointDescription(generateConfig.value.style)
  promptVariables.value['重点内容'] = generateConfig.value.focus || '按大纲发展'
  
  // 填充人物信息
  if (selectedMaterials.value.characters.length > 0) {
    const characterInfo = selectedMaterials.value.characters.map(char => {
      let info = `${char.name}（${getRoleText(char.role)}）\n`
      if (char.gender) {
        info += `性别：${getGenderText(char.gender)}\n`
      }
      if (char.age) {
        info += `年龄：${char.age}岁\n`
      }
      if (char.tags && char.tags.length > 0) {
        info += `标签：${char.tags.join('、')}\n`
      }
      if (char.personality) {
        info += `性格：${char.personality}\n`
      }
      if (char.appearance) {
        info += `外貌：${char.appearance}\n`
      }
      if (char.background) {
        info += `背景故事：${char.background}`
      }
      return info.trim()
    }).join('\n\n')
    promptVariables.value['主要人物'] = characterInfo
  }
  
  // 填充世界观信息
  if (selectedMaterials.value.worldSettings.length > 0) {
    const worldInfo = selectedMaterials.value.worldSettings.map(setting =>
      `${setting.title}：${setting.description || '暂无描述'}`
    ).join('\n')
    promptVariables.value['世界观设定'] = worldInfo
  }
  
  // 填充语料库信息
  if (selectedMaterials.value.corpus.length > 0) {
    const corpusInfo = selectedMaterials.value.corpus.map(item =>
      `【${item.title}】${item.content}`
    ).join('\n\n')
    promptVariables.value['参考语料'] = corpusInfo
  }
  
  generateFinalPrompt()
}

// 更新前文概要变量
const updateContextVariable = () => {
  if (selectedContextChapters.value.length > 0) {
    const contextChapters = selectedContextChapters.value.map(chapterId => {
      return props.chapters.find(ch => ch.id === chapterId)
    }).filter(Boolean)
    
    const contextInfo = contextChapters.map(ch => {
      const chapterIndex = getChapterIndex(ch)
      let chapterInfo = `第${chapterIndex}章《${ch.title}》\n`
      
      if (ch.description) {
        chapterInfo += `章节大纲：${ch.description}\n`
      }
      
      if (ch.content && ch.content.trim()) {
        const contentPreview = cleanHtmlForPreview(ch.content, 500)
        chapterInfo += `章节内容：${contentPreview}${ch.content.length > 500 ? '...' : ''}`
      }
      
      return chapterInfo
    }).join('\n\n')
    
    promptVariables.value['前文概要'] = contextInfo
  } else {
    promptVariables.value['前文概要'] = ''
  }
  
  generateFinalPrompt()
}

// 清空前文概要选择
const clearContextSelection = () => {
  selectedContextChapters.value = []
  updateContextVariable()
  ElMessage.success('已清空前文概要选择')
}

// 切换上下文章节
const toggleContextChapter = (chapterId) => {
  const index = selectedContextChapters.value.indexOf(chapterId)
  
  if (index > -1) {
    selectedContextChapters.value.splice(index, 1)
  } else {
    selectedContextChapters.value.push(chapterId)
  }
  
  updateContextVariable()
}

// 全选上下文章节
const selectAllContextChapters = () => {
  selectedContextChapters.value = availableContextChapters.value.map(ch => ch.id)
  updateContextVariable()
  ElMessage.success(`已选择所有${availableContextChapters.value.length}个章节`)
}

// 获取视角描述
const getViewpointDescription = (style) => {
  const styles = {
    'first-person': '第一人称',
    'third-person': '第三人称',
    'omniscient': '全知视角'
  }
  return styles[style] || '第三人称'
}

// 处理生成
const handleGenerate = () => {
  if (!selectedPrompt.value) {
    ElMessage.warning('请先选择提示词模板')
    return
  }
  
  emit('generate', {
    prompt: finalPrompt.value,
    config: generateConfig.value,
    materials: selectedMaterials.value,
    contextChapters: selectedContextChapters.value
  })
}

// 处理对话框关闭
const handleClose = () => {
  // 重置状态
  selectedMaterials.value = {
    characters: [],
    worldSettings: [],
    corpus: [],
    events: [],
    chapters: []
  }
  selectedContextChapters.value = []
  selectedPrompt.value = null
  promptVariables.value = {}
  finalPrompt.value = ''
  selectedContentCategory.value = 'content'
}
</script>

<style scoped>
.chapter-generate-content {
  padding: 0;
}

.generate-config-section {
  margin-bottom: 16px;
}

.config-card-modern {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.config-title {
  font-weight: 600;
  
}

.config-item {
  margin-bottom: 0;
}

.config-item :deep(.el-form-item__label) {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  
  margin: 0;
}

.materials-tabs {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.materials-tabs :deep(.el-tabs__header) {
  margin: 0;
  background-color: #f8f9fa;
}

.materials-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fafbfc;
  border-bottom: 1px solid #e4e7ed;
  min-height: 48px;
}

.tab-count {
  font-size: 12px;
  color: #606266;
}

/* 黑暗模式支持 */
html.dark .config-card-modern {
  border-color: var(--el-border-color);
}

html.dark .config-title {
  color: var(--el-text-color-primary);
}

html.dark .config-item :deep(.el-form-item__label) {
  color: var(--el-text-color-secondary);
}

html.dark .section-title {
  color: var(--el-text-color-primary);
}

html.dark .materials-tabs {
  border-color: var(--el-border-color);
}

html.dark .materials-tabs :deep(.el-tabs__header) {
  background-color: var(--el-fill-color);
}

html.dark .tab-header {
  background-color: var(--el-fill-color-light);
  border-bottom-color: var(--el-border-color);
}

html.dark .tab-count {
  color: var(--el-text-color-secondary);
}

.materials-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.material-card {
  border: 2px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #ffffff;
}

.material-card:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.material-card.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 0 0 1px #409eff;
}

.material-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.material-name {
  font-size: 14px;
  font-weight: 600;
  
  line-height: 1.2;
}

.material-desc {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.material-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.empty-materials {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.category-selection-modern {
  margin-bottom: 16px;
}

.category-header {
  font-size: 14px;
  font-weight: 600;
  
  margin-bottom: 12px;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 8px;
}

.category-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px;
  border: 2px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #ffffff;
}

.category-card:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.category-card.active {
  border-color: #409eff;
  background-color: #ecf5ff;
  color: #409eff;
}

.category-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.category-name {
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.prompt-selection-modern {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.prompt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  font-weight: 500;
  
}

.prompt-list-modern {
  max-height: 250px;
  overflow-y: auto;
  padding: 8px;
}

.prompt-item-modern {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #ffffff;
}

.prompt-item-modern:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.prompt-item-modern.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.prompt-content {
  flex: 1;
}

.prompt-title {
  font-size: 14px;
  font-weight: 600;
  
  margin: 0 0 4px 0;
}

.prompt-desc {
  font-size: 12px;
  color: #606266;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.prompt-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.prompt-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.prompt-actions {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-prompts {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.variables-section {
  margin-top: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.variables-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  font-weight: 500;
  
}

.variables-form {
  padding: 16px;
}

.variable-item {
  margin-bottom: 16px;
}

.variable-label {
  display: block;
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  margin-bottom: 4px;
}

.preview-section {
  margin-top: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  font-weight: 500;
  
}

.preview-actions {
  display: flex;
  gap: 8px;
}

.preview-content {
  padding: 16px;
}

.preview-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.materials-section,
.prompt-section {
  height: 650px;
  overflow-y: auto;
}

.materials-list {
  max-height: 300px;
  overflow-y: auto;
}

.chapter-material-card {
  padding: 14px;
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #fafbfc;
  min-height: 80px;
}

.chapter-material-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.chapter-material-card.selected {
  border-color: #409eff;
  background-color: #e6f4ff;
}

.chapter-material-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  gap: 8px;
}

.chapter-material-name {
  font-weight: 500;
  
  font-size: 14px;
  flex: 1;
}

.chapter-material-tags {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
  flex-wrap: wrap;
}

.chapter-material-desc {
  color: #666;
  font-size: 12px;
  line-height: 1.4;
  margin: 4px 0;
}

.chapter-material-content {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #eee;
}

.content-preview {
  color: #999;
  font-size: 11px;
  line-height: 1.3;
  font-style: italic;
}

.context-variable-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.context-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.context-chapter-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.context-chapter-option .chapter-title {
  font-size: 13px;
  
  font-weight: 500;
  flex: 1;
}

.context-chapter-option .chapter-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.context-chapter-option .word-count {
  font-size: 11px;
  color: #909399;
}

.context-tab-actions {
  display: flex;
  gap: 8px;
}

.material-meta {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #eee;
}

.event-time {
  color: #999;
  font-size: 11px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 全局黑暗模式支持 */
html.dark .material-card {
  border-color: var(--el-border-color);
  background-color: var(--el-fill-color);
}

html.dark .material-card:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.15);
}

html.dark .material-card.selected {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.2);
}

html.dark .material-name {
  color: var(--el-text-color-primary);
}

html.dark .material-desc {
  color: var(--el-text-color-secondary);
}

html.dark .empty-materials {
  color: var(--el-text-color-disabled);
}

html.dark .category-header {
  color: var(--el-text-color-primary);
}

html.dark .category-card {
  border-color: var(--el-border-color);
  background-color: var(--el-fill-color);
}

html.dark .category-card:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.15);
}

html.dark .category-card.active {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.2);
  color: #409eff;
}

html.dark .prompt-selection-modern {
  border-color: var(--el-border-color);
}

html.dark .prompt-header {
  background-color: var(--el-fill-color);
  border-bottom-color: var(--el-border-color);
  color: var(--el-text-color-primary);
}

html.dark .prompt-item-modern {
  border-color: var(--el-border-color);
  background-color: var(--el-fill-color);
}

html.dark .prompt-item-modern:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.15);
}

html.dark .prompt-item-modern.active {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.2);
}

html.dark .prompt-title {
  color: var(--el-text-color-primary);
}

html.dark .prompt-desc {
  color: var(--el-text-color-secondary);
}

html.dark .empty-prompts {
  color: var(--el-text-color-disabled);
}

html.dark .variables-section {
  border-color: var(--el-border-color);
}

html.dark .variables-header {
  background-color: var(--el-fill-color);
  border-bottom-color: var(--el-border-color);
  color: var(--el-text-color-primary);
}

html.dark .variable-label {
  color: var(--el-text-color-secondary);
}

html.dark .preview-section {
  border-color: var(--el-border-color);
}

html.dark .preview-header {
  background-color: var(--el-fill-color);
  border-bottom-color: var(--el-border-color);
  color: var(--el-text-color-primary);
}

html.dark .chapter-material-card {
  border-color: var(--el-border-color);
  background-color: var(--el-fill-color);
}

html.dark .chapter-material-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

html.dark .chapter-material-card.selected {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.2);
}

html.dark .chapter-material-name {
  color: var(--el-text-color-primary);
}

html.dark .chapter-material-desc {
  color: var(--el-text-color-secondary);
}

html.dark .content-preview {
  color: var(--el-text-color-disabled);
}

html.dark .context-chapter-option .chapter-title {
  color: var(--el-text-color-primary);
}

html.dark .context-chapter-option .word-count {
  color: var(--el-text-color-disabled);
}

html.dark .event-time {
  color: var(--el-text-color-disabled);
}

html.dark .material-meta {
  color: var(--el-text-color-disabled);
}
</style>
